<template>
  <view class="">
    <view v-if='list.length && hasLoaded' class="item" v-for="(item,i) in list" :key="i" @click="onClick(item)">
      <uni-card class="card">
        <template v-slot:title>
          <view class="title">
            <text class="commitTime">发起时间：{{item.commitTime}}</text>
            <uni-tag v-show="item.auditStatus === 5" text="已通过" type="success" size='small'></uni-tag>
            <uni-tag v-show="item.auditStatus === 1" text="待审核" type="primary" size='small'></uni-tag>
            <uni-tag v-show="item.auditStatus === 3" text="审核中" type="warning" size='small'></uni-tag>
            <uni-tag v-show="item.auditStatus === 2 || item.auditStatus === 4" text="未通过" type="error"
              size='small'></uni-tag>
            <uni-tag v-show="item.auditStatus === 0" text="已撤销" style='background-color: #888;color: #fff;' type=""
              size='small'></uni-tag>
          </view>
        </template>
        <view>开始时间: {{item.startTime}}</view>
        <view>结束时间: {{item.endTime}}</view>
        <view>加班时长: {{item.duration}}小时</view>
        <view>实际加班结束时间: {{item.realOvertime || '--'}}</view>

        <view v-if='!item.realOvertime && item.auditStatus === 5 && isTodayAfter(item)' class="end"
          @click.stop="onEnd(item)">
          结束加班
        </view>
      </uni-card>
    </view>
    <view v-if="!list.length && hasLoaded">
      <empty />
    </view>
    <uni-load-more v-if='list.length >= this.form.pageSize' :status="loadStatus" />

    <uni-popup type='dialog' ref='popup'>
      <uni-popup-dialog cancelText="关闭" confirmText="提交" type='warning' title="提示" @close="dialogClose"
        @confirm="dialogConfirm">
        <view class="dialog">
          <view><text>开始时间:</text> {{dialogForm.startTime}}</view>
          <view><text>结束时间:</text> {{dialogForm.endTime}}</view>
          <view><text>加班时长:</text> {{dialogForm.duration}}小时</view>
          <view v-if='dialogForm.eatStartTime'><text>吃饭开始时间:</text> {{dialogForm.eatStartTime}}</view>
          <view v-if='dialogForm.eatEndTime'><text>吃饭结束时间:</text> {{dialogForm.eatEndTime}}</view>
          <view v-if='dialogForm.eatDuration'><text>吃饭时长:</text> {{dialogForm.eatDuration}}小时</view>
          <view><text>实际加班时长:</text>
            {{dialogForm.realDuration > dialogForm.duration ? dialogForm.duration : dialogForm.realDuration}}小时
          </view>
        </view>
      </uni-popup-dialog>
    </uni-popup>
  </view>

</template>

<script>
  //import {formateDates,getCurrentMonthFirst,getCurrentMonthLast} from "@/common/util.js"
  import empty from '../../components/empty.vue'
  import {
    endOverTime,
    getAuditList,
    getClockConfig
  } from '../../utils/api'
  import {
    pointInsideCircle
  } from '../index/time'
import { singKey } from '../index/utils'
  import {
    jsonp
  } from 'vue-jsonp'
  export default {
    components: {
      empty
    },
    data() {
      return {
        isCompany: false,
        loadStatus: 'more',
        list: [],
        total: 0,
        hasLoaded: false,
        form: {
          page: 1,
          pageSize: 10,
          auditType: 3
        },
        dialogForm: {}
      }
    },

    onLoad() {
      this.getLocation()
      this.getList()
    },
    onPullDownRefresh() {
      this.form.page = 1
      this.getList()
    },
    onReachBottom() {
      console.log('onReachBottom')
      if (this.loadStatus === 'noMore') {
        return
      }
      this.form.page += 1
      this.getList()
    },
    methods: {
      // 获取当前位置
      async getLocation() {
        const {
          commonConfig
        } = await getClockConfig()
        const companyLatitude = commonConfig.clockLocationLatitude;
        const companyLongitude = commonConfig.clockLocationLongitude;
        var that = this;

        uni.getLocation({
          type: 'wgs84', //返回可以用于uni.openLocation的经纬度
          isHighAccuracy: true,
          success(res) {
            jsonp(`https://apis.map.qq.com/ws/coord/v1/translate`, {
              locations: res.latitude + ',' + res.longitude, 
              callbackQuery: 'callback',
              callbackName: 'jsonpCallback',
              key: singKey, 
              type: 1,
              output: 'jsonp',
            }).then(result => {
              console.log(result, 3)
              var s = pointInsideCircle([result.locations[0].lat,result.locations[0].lng], [companyLatitude, companyLongitude],
                commonConfig.clockRadius /
                100000);
              that.isCompany = s;
            }).catch(console.log)
            
          },
        });
      },
      async getList() {
        this.loadStatus = 'loading'
        const res = await getAuditList(this.form)
        this.total = res.dataCount
        if (this.form.page === 1) {
          this.list = res
        } else {
          this.list.push(...res)
        }
        uni.stopPullDownRefresh()

        if (this.total < this.form.pageSize) {
          this.loadStatus = 'noMore'
        } else
        if (this.list.length >= this.total) {
          this.loadStatus = 'noMore'
        } else {
          this.loadStatus = 'more'
        }
        this.hasLoaded = true
      },

      onClick(item) {
        uni.navigateTo({
          url: '/pages/leaveDetail/leaveDetail?id=' + item.id
        })
      },
      curTime() {
        // 创建一个Date对象，它会自动设置为当前日期和时间
        let now = new Date();

        // 获取年份
        let year = now.getFullYear();

        // 获取月份（注意：月份是从0开始的，所以我们需要加1）
        let month = now.getMonth() + 1;

        // 获取日期
        let date = now.getDate();

        // 获取小时（24小时制）
        let hours = now.getHours();

        // 获取分钟
        let minutes = now.getMinutes();

        // 获取秒
        let seconds = now.getSeconds();

        // 如果月份、日期、小时、分钟或秒数小于10，前面补一个'0'
        month = month < 10 ? '0' + month : month;
        date = date < 10 ? '0' + date : date;
        hours = hours < 10 ? '0' + hours : hours;
        minutes = minutes < 10 ? '0' + minutes : minutes;
        seconds = seconds < 10 ? '0' + seconds : seconds;

        // 拼接成字符串
        let formattedDateTime = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;

        return {
          formattedDate: formattedDateTime.slice(0, 10),
          full: formattedDateTime
        }
      },
      isTodayAfter(item) {
        const {
          formattedDate
        } = this.curTime()
        if (item.startTime.slice(0, 10) !== formattedDate) {
          return false
        }
        const now = +new Date()
        const startTime = +new Date(item.startTime)
        if (now <= startTime) {
          return false
        }
        return true
      },
      diffOvertime(start) {
        const startTime = new Date(start.replaceAll('-', '/')).getTime();
        const endTime = new Date().getTime(); // now

        let timeInterval = endTime - startTime;
        let hours = timeInterval / (1000 * 60 * 60);
        let roundedHours = Math.round(hours * 4) / 4;
        return roundedHours
      },
      onEnd(item) {
        if (!this.isCompany) {
          return uni.showToast({
            icon: 'none',
            title: '未在打卡范围内，无法操作'
          })
        }
        const realDuration = this.diffOvertime(item.startTime) - item.eatDuration
        this.dialogForm = {
          ...item,
          realDuration
        }
        if (realDuration <= 0) {
          this.$refs.popup.close()
          return uni.showToast({
            icon: 'none',
            title: '实际加班时长异常无法提交',
            duration: 3000
          })
        } else {
          this.$refs.popup.open()
        }
      },
      dialogClose() {
        this.$refs.popup.close()
      },
      dialogConfirm() {
        const {
          full
        } = this.curTime()
        const {
          realDuration,
          duration
        } = this.dialogForm
        const res = realDuration > duration ? duration : realDuration

        endOverTime({
          id: this.dialogForm.id,
          realOvertime: full,
          duration: res
        }).finally(() => {
          this.$refs.popup.close()
          this.form.page = 1
          this.getList()
        })
      }
    }
  }
</script>

<style lang="scss">
  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px;
    border-bottom: 1rpx dashed #929292;
  }

  .commitTime {
    font-size: 28rpx;
  }

  .card {
    position: relative;
  }

  .end {
    position: absolute;
    right: 8rpx;
    bottom: 8rpx;
    padding: 2rpx 8rpx;
    border-radius: 8rpx;
    font-size: 20rpx;
    background-color: coral;
    color: #fff;
  }

  .dialog {
    width: 100%;

    >view {
      display: flex;
      flex-direction: column;
      gap: 4rpx;

      &+view {
        margin-top: 12rpx;
      }
    }
  }
</style>